<?php

namespace App\Http\Controllers\WebPage\Admin;


use App\Http\Controllers\Controller;
use App\Http\Models\Video;
use App\Http\Models\VideoType;
use App\Services\Utils\Transaction;
use Illuminate\Http\Request;

/**
 * 视频curd
 * Class VideoController
 * @package App\Http\Controllers\WebPage\Admin
 */
class VideoController extends Controller
{

    public function index()
    {
        $videos = Video::orderBy('sort','DESC')->orderBy('id','DESC')->get();

        $types = VideoType::all()->sortByDesc('id');

        return  view('web-admin.video.video',compact('videos','types'));
    }

    public function store(Request $request)
    {
//        dd($request->all());
        $create = Video::create($request->all());

        if ( $create ) {
            return redirect()->back()->with('success','视频： "'. $create->name .'" 添加成功');
        } else {
            return redirect()->back()->withInput()->withErrors(' 添加失败,请重试');
        }
    }

    public function update(Request $request, $id)
    {

        $video = Video::find($id);

        $data = $request->all();

        $update = Transaction::handle(function () use ($video,$data) {

            $update_article = $video->update($data);

            return $update_article;
        });

        if ( $update ) {
            return redirect()->to(url()->previous() . "#tab_2")->with('success','更新成功');
        } else {
            return redirect()->back()->withInput()->withErrors('更新失败,请重试');
        }

    }


    public function destroy($id)
    {

        $del = Video::destroy($id);

        if ( $del ) {
            return redirect()->to(url()->previous() . "#tab_2")->with('success','视频删除成功');
        } else {
            return redirect()->back()->withInput()->withErrors(' 删除失败,请重试');
        }

    }

    public function edit($id)
    {
        $video = Video::find($id);

        return $video;
    }

}
